import { $ } from "../modules/public.js";
import ajax from "../modules/ajax.js";
import toast from "../modules/toast.js";
import dateParser from "../modules/dateParser.js";


let userData = await ajax({
  url:"http://localhost:3000/getuser",
  data:{
    token:sessionStorage.getItem("token") || ""
  }
})
userData = JSON.parse(userData);
if(userData.code === 0){
  toast({
    type:"error",
    title:"缺少必传参数",
    close:()=>{
      location.assign("./login.html");
    }
  })
}
if(userData.code === 3){
  toast({
    type:"error",
    title:"数据库出错"
  })
}
if(userData.code === 2){
  toast({
    type:"error",
    title:"登录失效，或，当前未登录，请重新登录",
    close:()=>{
      location.assign("./login.html");
    }
  })
}


if(userData.code === 1){
  const userMsg = userData.data;

  let teamData = await ajax({
    url: "http://localhost:3000/getteam"
  })
  teamData = JSON.parse(teamData).data;

  let str = "";
  teamData.forEach(val=>{
    str += `<option ${val.tCode === userMsg.team ? "selected" : ""} value="${val.tCode}">${val.tName}</option>`
  })
  $(".team").innerHTML = str;

  $(".avatar img").src = userMsg.avatar || "";
  $(".nickName").value = userMsg.nickName || "";
  $(".tel").innerText = userMsg.tel || "";
  $(".email").value = userMsg.email || "";
  $(".team").value = userMsg.team || "";

  let bStr = "";
  if(userMsg.birth){
    const d = new Date(userMsg.birth);
    bStr = dateParser(d);
  }
  $(".birth").value = bStr;
  
  $(".power").innerText = userMsg.power===0 ? "用户" : "管理员";
  const registerD = new Date(userMsg.registerTime);
  $(".registerTime").innerText = registerD.toLocaleString();
  
  let loginTimeStr = "";
  if(userMsg.loginTime){
    const loginD = new Date(userMsg.loginTime);
    loginTimeStr = loginD.toLocaleString();
  }
  $(".loginTime").innerText = loginTimeStr;
}

$(".openSetPw").onclick = function(){
  $(".setPasswordBox").style.display = "flex";
  $(".oldPassword").value = "";
  $(".newPassword").value = "";
}
$(".setPasswordBox .close").onclick = function(){
  $(".setPasswordBox").style.display = "none";
}

$(".setPW").onclick = function(){
  ajax({
    url:"http://localhost:3000/setpassword",
    method:"post",
    data:{
      token: sessionStorage.getItem("token"),
      oldPassword: $(".oldPassword").value,
      newPassword: $(".newPassword").value
    }
  }).then(res=>{
    res = JSON.parse(res);
    toast({
      type: "info",
      title: res.msg,
      close:()=>{
        $(".setPasswordBox").style.display = "none";
        sessionStorage.removeItem("token");
        location.assign("./login.html");
      }
    })
  })
}

// 初始获取个人信息
let nickNameStr = $(".nickName").value;
let emailStr = $(".email").value;
let birthStr = $(".birth").value;
let teamStr = $(".team").value;
// 如果个人信息发生修改，获取最新信息
$(".nickName").onchange = function(){
  nickNameStr = this.value;
}
$(".email").onchange = function(){
  emailStr = this.value;
}
$(".birth").onchange = function(){
  birthStr = this.value;
}
$(".team").onchange = function(){
  teamStr = this.value;
}
// 点击保存，向后端发起修改个人信息请求，并携带各种数据
$(".save").onclick = function(){
  const data = {
    token: sessionStorage.getItem("token")
  };
  // 根据是否存在指定信息，决定向后端发送哪些数据
  if(nickNameStr) data.nickName = nickNameStr;
  if(emailStr) data.email = emailStr;
  if(birthStr) data.birth = birthStr;
  if(teamStr) data.team = teamStr;
  ajax({
    url:"http://localhost:3000/setuser",
    method:"post",
    data
  }).then(res=>{
    res = JSON.parse(res);
    toast({
      type: "info",
      title: res.msg
    })
  })
}

$(".quit").onclick = function(){
  sessionStorage.removeItem("token");
  location.assign("./index.html")
}

$(".setAvatar").onclick = function(){

  $(".token").value = sessionStorage.getItem("token");
  
  // 利用本地对象FormData，转换表单中的文件信息
  const fd = new FormData( $(".avatarForm") );

  console.log(fd)
  
  const xhr = new XMLHttpRequest();
  xhr.open("post", "http://localhost:3000/setavatar");
  // 将文件信息，直接传给xhr的send方法，发送到后端
  xhr.send( fd );
  xhr.onload = function(){
    if(xhr.status === 200){
      const res = JSON.parse(xhr.responseText);
      if(res.code === 1){
        toast({
          type: "success",
          title: "修改成功"
        })
        $(".avatar img").src = res.data;
      }else{
        console.log(res);
        toast({
          type: "error",
          title: res.msg
        })
      }
    }
  }
}